package cn.gcjxsc.controller;

import cn.gcjxsc.exception.SQLException;
import com.zgxl.common.util.AjaxResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author pumbaa
 * @since 1.0
 */
@RestControllerAdvice
public class GlobalErrorHandler {
    protected Logger logger = LoggerFactory.getLogger(GlobalErrorHandler.class);

    @ExceptionHandler(value = SQLException.class)
    public AjaxResponse SqlExceptionHandler(HttpServletRequest req, Exception e) {
        log(req, e);
        return AjaxResponse.ajaxFailure(e.getMessage());
    }

    @ExceptionHandler(value = TypeMismatchException.class)
    public AjaxResponse paramTypeExceptionHandler(HttpServletRequest req, Exception e) {
        log(req, e);
        return AjaxResponse.ajaxFailure("参数类型不正确");
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public AjaxResponse paramExceptionHandler(HttpServletRequest req, Exception e) {
        log(req, e);
        return AjaxResponse.ajaxFailure("参数数量不正确");
    }

    @ExceptionHandler(value = Exception.class)
    public AjaxResponse defaultExceptionHandler(HttpServletRequest req, Exception e){
        log(req, e);
        return AjaxResponse.ajaxFailure("内部处理出错");
    }
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public AjaxResponse noHandlerFoundExceptionHandler(HttpServletRequest req, Exception e){
        log(req, e);
        return AjaxResponse.ajaxFailure("请求的资源不存在");
    }

    private void log(HttpServletRequest req, Exception e) {
        String msg = "URI:" + req.getRequestURI() + ", 错误:" + e.getMessage();
        logger.error(msg);
        e.printStackTrace();
    }
}
